package com.demo.server.handler;

import com.demo.common.protocal.MyMessage;
import com.demo.common.protocal.OpType;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class ConnectHandler extends ChannelInboundHandlerAdapter {

    private volatile AtomicInteger onlineCount = new AtomicInteger(0);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msgObj) throws Exception {
        MyMessage msg = (MyMessage) msgObj;
        if (OpType.PING == msg.getType() || OpType.PONG == msg.getType()) {
            log.debug("Client message： type：{}, body length：{}, body：{}", msg.getType(), msg.getContentLength(), msg.getContent());
            ctx.writeAndFlush(MyMessage.PongMessage());
        } else {
            ctx.fireChannelRead(msg);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        final int count = onlineCount.incrementAndGet();
        log.debug("Number of online device：{}", count);
        ctx.fireChannelActive();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        final int count = onlineCount.decrementAndGet();
        log.debug("Number of online device：{}", count);
        ctx.fireChannelInactive();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("服务器读取数据异常");
        super.exceptionCaught(ctx, cause);
        ctx.close();
    }
}
